<template>
  <view>
    <!-- 统一的工作台模块 -->
    <view class="work-container">
      <!-- 顶部统计信息卡片（需要首页权限） -->
      <view class="header-card" v-if="(isStaff || isAdmin) && hasPermission('首页')">
        <view class="header-top-bar">
          <text class="iconfont icon-close" @click="goBack"></text>
          <text class="header-main-title">昨日<span class="highlight">收款金额</span></text>
          <text class="iconfont icon-refresh" @click="refreshStats" :class="{ 'loading': yesterdayStats.loading }"></text>
        </view>
        <view class="header-main-value">
          <text v-if="yesterdayStats.loading" class="loading-text">数据加载中...</text>
          <text v-else>{{ yesterdayStats.settlementAmount }}</text>
        </view>
        <view class="header-stats-row">
          <view class="header-stat-item">
            <text class="header-stat-label">昨日<span class="highlight">订单数</span></text>
            <text class="header-stat-value">{{ yesterdayStats.orderCount }}</text>
          </view>
          <view class="header-stat-item">
            <text class="header-stat-label">昨日<span class="highlight">退费金额</span></text>
            <text class="header-stat-value">{{ yesterdayStats.refundAmount }}</text>
          </view>
        </view>
      </view>

      <!-- 缴费统计信息（需要首页权限） -->
      <view class="stats-card" v-if="(isStaff || isAdmin) && hasPermission('首页')">
        <view class="card-title">
          <view class="title-icon">
            <uni-icons type="wallet" size="20" color="#6fc16f"></uni-icons>
          </view>
          <text class="title-text">缴费统计</text>
        </view>
        <view class="pay-stats-row">
          <view class="pay-stat">
            <text class="pay-num">{{ payStats.totalCount }}</text>
            <text class="pay-label">总数量</text>
          </view>
          <view class="pay-stat">
            <text class="pay-num">{{ payStats.todayOrderCount }}</text>
            <text class="pay-label">今日缴费</text>
          </view>
          <view class="pay-stat">
            <text class="pay-num">{{ payStats.endDateCount }}</text>
            <text class="pay-label">欠费数量</text>
          </view>
        </view>
      </view>

      <!-- 系统功能模块 -->
      <view class="function-section">
        <view class="section-title">
          <view class="section-title-line"></view>
          <text class="section-title-text">系统功能</text>
          <view class="section-title-line"></view>
        </view>
        
        <view class="function-grid">
          <!-- 基础缴费功能（也需要权限控制） -->
          <view class="function-item" v-if="hasPermission('人脸门禁缴费')" @click="handleToPayment">
            <view class="function-icon-wrapper" style="background: linear-gradient(135deg, #007AFF 0%, #0051D5 100%);">
              <uni-icons type="wallet" size="26" color="#fff"></uni-icons>
            </view>
            <text class="function-text">人脸门禁缴费</text>
          </view>
          <view class="function-item" v-if="hasPermission('缴纳运维费')" @click="handleToMaintenance">
            <view class="function-icon-wrapper" style="background: linear-gradient(135deg, #07c160 0%, #00a047 100%);">
              <uni-icons type="vip" size="26" color="#fff"></uni-icons>
            </view>
            <text class="function-text">缴纳运维费</text>
          </view>
          <view class="function-item" v-if="hasPermission('购买门禁卡')" @click="handleToAccessCard">
            <view class="function-icon-wrapper" style="background: linear-gradient(135deg, #ff9900 0%, #e68200 100%);">
              <uni-icons type="cart" size="26" color="#fff"></uni-icons>
            </view>
            <text class="function-text">购买门禁卡</text>
          </view>

          <!-- 管理功能（根据权限显示） -->
          <view class="function-item" v-if="hasPermission('地址录入')" @click="goTo('/pages/address/input')">
            <view class="function-icon-wrapper" style="background: linear-gradient(135deg, #69C6E3 0%, #4ab3d1 100%);">
              <uni-icons type="location-filled" size="26" color="#fff"></uni-icons>
            </view>
            <text class="function-text">账单录入</text>
          </view>
          <view class="function-item" v-if="hasPermission('资料查询')" @click="goTo('/pages/data/query')">
            <view class="function-icon-wrapper" style="background: linear-gradient(135deg, #F5A623 0%, #d4921e 100%);">
              <uni-icons type="search" size="26" color="#fff"></uni-icons>
            </view>
            <text class="function-text">资料查询</text>
          </view>
          <view class="function-item" v-if="hasPermission('缴费记录')" @click="goTo('/pages/payment/record')">
            <view class="function-icon-wrapper" style="background: linear-gradient(135deg, #579BDB 0%, #4682c4 100%);">
              <uni-icons type="list" size="26" color="#fff"></uni-icons>
            </view>
            <text class="function-text">缴费记录</text>
          </view>
          <view class="function-item" v-if="hasPermission('账单管理')" @click="goTo('/pages/bills/manage')">
            <view class="function-icon-wrapper" style="background: linear-gradient(135deg, #6C5CE7 0%, #5a54d6 100%);">
              <uni-icons type="paperplane" size="26" color="#fff"></uni-icons>
            </view>
            <text class="function-text">账单管理</text>
          </view>
          <view class="function-item" v-if="hasPermission('房东管理')" @click="goTo('/pages/landlord/manage')">
            <view class="function-icon-wrapper" style="background: linear-gradient(135deg, #9B72D3 0%, #8460c4 100%);">
              <uni-icons type="home-filled" size="26" color="#fff"></uni-icons>
            </view>
            <text class="function-text">房东管理</text>
          </view>

          <!-- 员工专用功能 -->
          <view class="function-item" v-if="hasPermission('退款管理')" @click="goTo('/pages/refund/manage')">
            <view class="function-icon-wrapper" style="background: linear-gradient(135deg, #FA7B72 0%, #f45b52 100%);">
              <uni-icons type="wallet-filled" size="26" color="#fff"></uni-icons>
            </view>
            <text class="function-text">退款管理</text>
          </view>
          <view class="function-item" v-if="hasPermission('欠费催缴')" @click="goTo('/pages/arrears/reminder')">
            <view class="function-icon-wrapper" style="background: linear-gradient(135deg, #7DBB57 0%, #6da647 100%);">
              <uni-icons type="notification-filled" size="26" color="#fff"></uni-icons>
            </view>
            <text class="function-text">欠费催缴</text>
          </view>
          <view class="function-item" v-if="hasPermission('工单管理')" @click="goTo('/pages/workorder/manage')">
            <view class="function-icon-wrapper" style="background: linear-gradient(135deg, #F5A623 0%, #d4921e 100%);">
              <uni-icons type="calendar-filled" size="26" color="#fff"></uni-icons>
            </view>
            <text class="function-text">工单管理</text>
          </view>
          <view class="function-item" v-if="hasPermission('充电桩报装')" @click="goTo('/运营管理/充电桩报装')">
            <view class="function-icon-wrapper" style="background: linear-gradient(135deg, #7DBB57 0%, #6da647 100%);">
              <uni-icons type="paperplane-filled" size="26" color="#fff"></uni-icons>
            </view>
            <text class="function-text">充电桩报装</text>
          </view>

          <!-- 运维人员专用功能 -->
          <view class="function-item" v-if="hasPermission('接收工单')" @click="goTo('/pages/workorder/todo')">
            <view class="function-icon-wrapper" style="background: linear-gradient(135deg, #FF6B6B 0%, #ff4757 100%);">
              <uni-icons type="list" size="26" color="#fff"></uni-icons>
            </view>
            <text class="function-text">接收工单</text>
          </view>

          <!-- 新增功能菜单 -->
          <view class="function-item" v-if="hasPermission('门禁机替换')" @click="goTo('/pages/device/replace')">
            <view class="function-icon-wrapper" style="background: linear-gradient(135deg, #8B5CF6 0%, #7C3AED 100%);">
              <uni-icons type="gear" size="26" color="#fff"></uni-icons>
            </view>
            <text class="function-text">门禁机替换</text>
          </view>

          <!-- admin专属功能 -->
          <view class="function-item" v-if="isAdmin" @click="goTo('/pages/admin/system')">
            <view class="function-icon-wrapper" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);">
              <uni-icons type="settings" size="26" color="#fff"></uni-icons>
            </view>
            <text class="function-text">系统管理</text>
          </view>
          <view class="function-item" v-if="isAdmin" @click="goTo('/pages/admin/users')">
            <view class="function-icon-wrapper" style="background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);">
              <uni-icons type="contact" size="26" color="#fff"></uni-icons>
            </view>
            <text class="function-text">用户管理</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { getYesterdayStats } from '@/api/door/order-static'

export default {
  computed: {
    isStaff() {
      const roles = this.$store.state.user.roles || [];
      return roles.includes('yg');
    },
    isYunwei() {
      const roles = this.$store.state.user.roles || [];
      return roles.includes('yunwei');
    },
    isAdmin() {
      const roles = this.$store.state.user.roles || [];
      return roles.includes('admin');
    },
    // 判断是否应该显示统计信息
    shouldShowStats() {
      return (this.isStaff || this.isAdmin) && this.hasPermission('首页');
    },
    // 获取用户拥有的路由权限菜单名称
    allowedMenus() {
      const routers = this.$store.state.user.routers || [];
      const allowedMenuNames = new Set(); // 使用Set避免重复
      
      // 递归遍历路由配置，收集所有可访问的菜单
      const collectMenus = (routerList) => {
        routerList.forEach(router => {
          // 如果路由有meta.title，添加到权限列表
          if (router.meta && router.meta.title) {
            allowedMenuNames.add(router.meta.title);
          }
          
          // 如果有children，递归处理
          if (router.children && router.children.length > 0) {
            router.children.forEach(child => {
              if (child.meta && child.meta.title) {
                allowedMenuNames.add(child.meta.title);
              }
              // 如果child还有children，继续递归
              if (child.children && child.children.length > 0) {
                collectMenus(child.children);
              }
            });
          }
        });
      };
      
      collectMenus(routers);
      return Array.from(allowedMenuNames);
    }
  },
  data() {
    return {
      userInfo: {
        name: '',
        avatar: ''
      },
      // 昨日统计数据
      yesterdayStats: {
        settlementAmount: '数据暂未更新',
        orderCount: '数据暂未更新',
        refundAmount: '数据暂未更新',
        loading: false
      },
      // 缴费管理统计数据
      payStats: {
        totalCount: '数据暂未更新',
        todayOrderCount: '数据暂未更新',
        endDateCount: '数据暂未更新'
      },
      swiper: {
        current: 0,
        swiperDotIndex: 0,
        data: [
          { image: '/static/images/banner/banner01.jpg' },
          { image: '/static/images/banner/banner02.jpg' },
          { image: '/static/images/banner/banner03.jpg' }
        ]
      }
    }
  },
  watch: {
    // 监听统计显示权限变化
    shouldShowStats(newVal, oldVal) {
      console.log('shouldShowStats 变化:', { oldVal, newVal });
      if (newVal && !oldVal && !this.yesterdayStats.loading) {
        console.log('权限变化触发：开始获取统计数据');
        this.getYesterdayStatsData();
      }
    }
  },
  
  onLoad() {
    // 获取用户数据
    const userStore = this.$store.state.user;
    if (userStore) {
      this.userInfo.name = userStore.name || '';
      this.userInfo.avatar = userStore.avatar || '';
    }
    
    // 检查路由权限数据，如果为空且用户已登录，则重新获取
    this.checkAndRefreshRouters();
  },
  
  mounted() {
    // 在组件完全挂载后，再次检查是否需要获取统计数据
    setTimeout(() => {
      this.checkAndLoadStats();
    }, 500);
  },
  
  // 下拉刷新
  onPullDownRefresh() {
    if (this.shouldShowStats) {
      this.getYesterdayStatsData().then(() => {
        uni.stopPullDownRefresh();
      }).catch(() => {
        uni.stopPullDownRefresh();
      });
    } else {
      uni.stopPullDownRefresh();
    }
  },
  methods: {
    // 检查是否有特定权限
    hasPermission(menuName) {
      // admin用户拥有所有权限
      if (this.isAdmin) {
        console.log(`Admin用户访问菜单: ${menuName} - 允许`);
        return true;
      }
      
      // 所有角色（包括员工和运维）都需要检查路由权限
      const hasAccess = this.allowedMenus.includes(menuName);
      console.log(`用户访问菜单: ${menuName} - ${hasAccess ? '允许' : '拒绝'}`);
      if (!hasAccess) {
        console.log(`可访问的菜单列表:`, this.allowedMenus);
        console.log(`查找的菜单名称: "${menuName}"`);
      }
      return hasAccess;
    },
    goBack() {
      uni.navigateBack();
    },
    goTo(path) {
      if (path) {
        uni.navigateTo({ url: path });
      }
    },
    handleToLogin() {
      // 切换账号逻辑
      //清除所有缓存
      uni.clearStorageSync();
      uni.navigateTo({
        url: '/'
      });
    },
    payNow() {
      // 立即支付逻辑
      this.$modal.showToast('支付功能开发中');
    },
    showCouponDetails() {
      // 显示优惠信息详情
      uni.showModal({
        title: '优惠详情',
        content: '一次性缴费12个月可免费获赠2个月使用时长，共计14个月服务期。该优惠活动长期有效。',
        showCancel: false,
        confirmText: '我知道了'
      });
    },
    clickBannerItem(item) {
      console.info(item)
    },
    changeSwiper(e) {
      this.swiper.current = e.detail.current
    },
    handleToPayment() {
      this.$tab.navigateTo('/pages/mine/payment/index');
    },
    handleToMaintenance() {
      this.$tab.navigateTo('/pages/mine/maintenance/index');
    },
    handleToAccessCard() {
      this.$tab.navigateTo('/pages/mine/accesscard/index');
    },
    
    // 获取昨日统计数据
    async getYesterdayStatsData() {
      if (this.yesterdayStats.loading) return;
      
      this.yesterdayStats.loading = true;
      try {
        const response = await getYesterdayStats();
        if (response.code === 200 && response.data) {
          const data = response.data;
          // 更新昨日统计数据
          this.yesterdayStats = {
            settlementAmount: data.yesterdayPayAmount ? `¥${data.yesterdayPayAmount}` : '¥0.00',
            orderCount: data.yesterdayOrderCount || '0',
            refundAmount: data.yesterdayRefundAmount ? `¥${data.yesterdayRefundAmount}` : '¥0.00',
            loading: false
          };
          // 更新缴费管理统计数据
          this.payStats = {
            totalCount: data.totalCount || '0',
            todayOrderCount: data.todayOrderCount || '0',
            endDateCount: data.endDateCount || '0'
          };
        } else {
          console.error('获取昨日统计数据失败:', response.msg);
          this.$modal.msgError(response.msg || '获取数据失败');
        }
      } catch (error) {
        console.error('获取昨日统计数据异常:', error);
        this.$modal.msgError('网络异常，请稍后重试');
      } finally {
        this.yesterdayStats.loading = false;
      }
    },
    
    // 刷新统计数据
    refreshStats() {
      if (this.shouldShowStats) {
        this.getYesterdayStatsData();
      }
    },

    // 检查并刷新路由权限
    async checkAndRefreshRouters() {
      // 检查用户是否已登录
      const token = this.$store.state.user.token;
      if (!token) {
        console.log('用户未登录，跳过路由权限检查');
        return;
      }
      
      const userRouters = this.$store.state.user.routers;
      if (!userRouters || userRouters.length === 0) {
        console.log('路由权限数据为空，尝试重新获取...');
        try {
          await this.$store.dispatch('FetchRouters');
          console.log('路由权限数据已更新');
          
          // 权限数据更新后，检查是否需要获取统计数据
          this.$nextTick(() => {
            this.checkAndLoadStats();
          });
        } catch (error) {
          console.error('刷新路由权限失败:', error);
          // 不显示错误提示，避免在正常访问时打扰用户
          console.warn('可能是普通用户或接口暂时不可用');
        }
      } else {
        console.log('路由权限数据已存在，无需重复获取');
        // 权限数据已存在，立即检查是否需要获取统计数据
        this.$nextTick(() => {
          this.checkAndLoadStats();
        });
      }
    },
    
    // 检查并加载统计数据
    checkAndLoadStats() {
      console.log('检查统计数据权限...');
      console.log('用户角色:', { isStaff: this.isStaff, isAdmin: this.isAdmin });
      console.log('首页权限:', this.hasPermission('首页'));
      console.log('应该显示统计:', this.shouldShowStats);
      
      if (this.shouldShowStats && !this.yesterdayStats.loading) {
        console.log('开始获取统计数据');
        this.getYesterdayStatsData();
      } else {
        console.log('不需要获取统计数据或正在加载中');
      }
    }
  }
}
</script>

<style lang="scss" scoped>
/* 整体容器样式 */
.work-container {
  background: linear-gradient(180deg, #f8fafc 0%, #edf2f7 100%);
  min-height: 100vh;
  padding: 24rpx 24rpx 80rpx;
  box-sizing: border-box;
}

/* 刷新图标动画 */
.icon-refresh {
  transition: transform 0.3s ease;
  cursor: pointer;
  
  &.loading {
    animation: rotate 1s linear infinite;
  }
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

/* 加载文本样式 */
.loading-text {
  opacity: 0.8;
  font-style: italic;
}

/* 高亮文字样式 */
.highlight {
  font-weight: bold;
}

/* 顶部统计卡片优化 */
.header-card {
  background: linear-gradient(135deg, #6fc16f 0%, #4CAF50 100%);
  padding: 40rpx;
  margin-bottom: 24rpx;
  border-radius: 24rpx;
  color: #fff;
  box-shadow: 0 8rpx 32rpx rgba(111, 193, 111, 0.3);
  
  .header-top-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24rpx;
    
    .iconfont {
      font-size: 40rpx;
      opacity: 0.9;
    }
    
    .header-main-title {
      font-size: 34rpx;
      font-weight: 600;
    }
  }
  
  .header-main-value {
    text-align: center;
    font-size: 52rpx;
    font-weight: bold;
    margin: 32rpx 0;
    text-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
  }
  
  .header-stats-row {
    display: flex;
    justify-content: space-around;
    align-items: center;
    padding-top: 32rpx;
    border-top: 1px solid rgba(255, 255, 255, 0.25);
    
    .header-stat-item {
      position: relative;
      flex: 1;
      text-align: center;
      
      &:first-child::after {
        content: '';
        position: absolute;
        right: 0;
        top: 50%;
        transform: translateY(-50%);
        width: 1px;
        height: 60%;
        background-color: rgba(255, 255, 255, 0.25);
      }
      
      .header-stat-label {
        font-size: 24rpx;
        opacity: 0.85;
        margin-bottom: 8rpx;
      }
      
      .header-stat-value {
        display: block;
        font-size: 36rpx;
        font-weight: bold;
      }
    }
  }
}

/* 统计卡片样式优化 */
.stats-card {
  background: #fff;
  border-radius: 20rpx;
  margin-bottom: 24rpx;
  padding: 32rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
  
  .card-title {
    display: flex;
    align-items: center;
    margin-bottom: 24rpx;
    padding-bottom: 16rpx;
    border-bottom: 1px solid #f5f5f5;
    
    .title-icon {
      width: 48rpx;
      height: 48rpx;
      background: rgba(111, 193, 111, 0.1);
      border-radius: 12rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 16rpx;
    }
    
    .title-text {
      font-size: 32rpx;
      font-weight: 600;
      color: #333;
    }
  }
}

.pay-stats-row {
  display: flex;
  justify-content: space-around;
  align-items: center;
  
  .pay-stat {
    position: relative;
    flex: 1;
    text-align: center;
    
    &:not(:last-child)::after {
      content: '';
      position: absolute;
      right: 0;
      top: 50%;
      transform: translateY(-50%);
      width: 1px;
      height: 60rpx;
      background-color: #f0f0f0;
    }
    
    .pay-num {
      font-size: 44rpx;
      color: #333;
      font-weight: 700;
      margin-bottom: 8rpx;
    }
    
    .pay-label {
      display: block;
      font-size: 24rpx;
      color: #888;
    }
  }
}

/* 功能区域样式优化 */
.function-section {
  background: #fff;
  border-radius: 20rpx;
  padding: 32rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
}

.section-title {
  display: flex;
  align-items: center;
  margin-bottom: 32rpx;
  
  .section-title-line {
    flex: 1;
    height: 1px;
    background: linear-gradient(90deg, transparent 0%, #e2e8f0 50%, transparent 100%);
  }
  
  .section-title-text {
    margin: 0 24rpx;
    font-size: 30rpx;
    font-weight: 600;
    color: #334155;
  }
}

.function-grid {
  display: flex;
  flex-wrap: wrap;
  margin: -12rpx;
}

.function-item {
  width: 25%;
  padding: 12rpx;
  box-sizing: border-box;
  
  .function-icon-wrapper {
    width: 80rpx;
    height: 80rpx;
    border-radius: 20rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 0 auto 16rpx;
    box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.15);
    transition: all 0.3s ease;
    
    &:active {
      transform: translateY(2rpx);
      box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.2);
    }
  }
  
  .function-text {
    display: block;
    text-align: center;
    font-size: 24rpx;
    color: #475569;
    font-weight: 500;
    line-height: 1.4;
  }
}

/* 响应式适配 */
@media (max-width: 750rpx) {
  .function-item {
    width: 33.33%;
  }
}

@media (max-width: 600rpx) {
  .function-item {
    width: 50%;
  }
}

/* 点击反馈效果 */
.function-item {
  transition: all 0.2s ease;
  
  &:active {
    transform: scale(0.95);
    opacity: 0.8;
  }
}

/* 卡片悬浮效果 */
.header-card,
.stats-card,
.function-section {
  transition: all 0.3s ease;
  
  &:hover {
    box-shadow: 0 8rpx 40rpx rgba(0, 0, 0, 0.12);
  }
}
</style> 